Contents
- 1. Introduction
- 2. Adding Nodes
- 3. Removing Nodes
- 4. TreeView Styles
- 5. Using Images
- 6. Editing Labels
- 7. Expanding Items
- 8. Drag and Drop
Downloads
Related Categories
TreeView Control - Adding Nodes
Adding Nodes
Adding an item, or Node to the TreeView control is simple, once you know how. Adding a node uses the following syntax:
TreeView1.Nodes.Add Relative, Relationship, Key, Text, Image, SelectedImageAll of this parameters are optional. As the TreeView control is made up of items in a Tree, Visual Basic needs to know where the new item goes. You use Relative and Relationship to specify this. Relative specifies a relation (an existing node) to the new node you are creating. Relationship specifies how the new node is related to this existing node. Possible relationships are:
tvwChild '// new node is a child (one level down) of the specified node
tvwFirst '// new node is first, at the same level of the specified node
tvwLast '// new node is last, at the same level of the specified node
tvwNext '// new node is after (at the same level) the specified node
tvwPrevious '// new node is before (at the same level) the specified nodeKey is a unique indentifier for this node (but easier to remember than an Index ID), which can be a string. Text is the text to be displayed for this node. Image is the image to be displayed next to the node, specified from the bound Image List (discussed later), such as a folder. SelectedImage is the image to be displayed when the node is selected, such as an open folder, specified from the bound Image list (discussed later). Add a TreeView control to your form and enter the code below.
Private Sub Form_Load()
'// add some items
TreeView1.Nodes.Add , , "root", "Root Item"
TreeView1.Nodes.Add "root", tvwChild, "child1_root", "Child1 of Root"
TreeView1.Nodes.Add "root", tvwChild, "child2_root", "Child2 of Root"
TreeView1.Nodes.Add "child1_root", tvwChild, "child1_child1", "Child1 of Child1"
'// make sure Child1 of Child1 is visible
TreeView1.Nodes("child1_child1").EnsureVisible
End SubRun the project. You should see something like the image below:
![]()
Notice that the last line in the Form_Load procedure uses the EnsureVisible method. This forces the specified node to become visible, by expanding another item in needed.
James first started writing tutorials on Visual Basic in 1999 whilst starting this website (then known as VB Web). Since then, the site has grown rapidly, and James has written numerous tutorials, articles and reviews on VB, PHP, ASP and C#. In October 2003, James formed the company Developer Fusion Ltd, which owns this website, and also offers various development services. In his spare time, he's a 3rd year undergraduate studying Computer Science in the UK. He's also a Visual Basic MVP.